package html;

import java.awt.FileDialog;
import java.awt.Frame;

import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class HtmlPage implements FilenameFilter{

	private HtmlBody htmlBody;
	private String tittle;
	List<String> css;
	
	public HtmlPage(String name,HtmlBody body){
		htmlBody=body;
		tittle=name;
		css= new ArrayList<String>();
		css.add("Table.css");
	}
	
	public static final String dir = "/html/resource/";
	
	public String toString(){
		StringBuffer res=new StringBuffer();
		add(res,"begin.html");
		res.append("<title>"+tittle+"</title>");
		res.append("<style type=\"text/css\">");
		for(String c:css)
			add(res,c);
		res.append("</style>");
		add(res,"Middle.html");
		res.append(htmlBody.getHtmlBody());
		add(res,"End.html");
		return res.toString();
	}
	
	private void add(StringBuffer res, String resource){
		Scanner s =new Scanner(HtmlPage.class.getResourceAsStream(dir+resource));
		s.useDelimiter("\n");
		while(s.hasNext()){
			res.append(s.next());
			res.append("\n");
		}
		s.close();
		
	}
	
	public void exportToFile(Frame owner){
		FileDialog f =new FileDialog(owner,"Enregistrer dans quel Fichier");
		f.setMode(FileDialog.SAVE);
		f.setFilenameFilter(this);	
		f.setVisible(true);	
		FileWriter file;
		try {
			file = new FileWriter(f.getDirectory()+f.getFile()+(accept(null,f.getDirectory()+f.getFile())?(""):(".html")));
			file.write(toString());
			file.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}




	public boolean accept(File arg0, String arg1) {
		return arg1.substring(arg1.length()-5).equals(".html");		
	}

}
